package com.fagp.register.controller;

import com.fagp.register.provide.AucFeignService;
import com.zebra.common.concurrent.ZebraExecutorManager;
import com.zebra.register.RegisterConfigInfoManager;
import com.zebra.register.RelationService;
import com.zebra.register.ServerRedisService;
import com.zebra.remoting.config.RegisterServerInfo;
import com.zebra.remoting.config.TmsServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;


@RestController
@Slf4j
public class RegisterController {

    @Autowired
    private ServerRedisService serverRedisService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private AucFeignService aucFeignService;


    @GetMapping(value = "/relation/ping")
    @ResponseBody
    public Integer ping(){
        return 1;
    }


    /**
     *   relation/follower/{}/{}/{}/{}", leader.getInIP(), leader.getPort(),
     * follower send msg to leader
     *  if myself is leader send msg[leader info] to follower;
     *  if myself is not leader: 肯定是leader 【该处简单处理】
     * @param serverid
     * @param inip
     * @param port
     * @return
     */
    @GetMapping(value = "/relation/follower/{serverid}/{inip}/{port}/{oldid}")
    @ResponseBody
    public Integer registerFollower(@PathVariable("serverid") int serverid,
                                    @PathVariable("inip") String inip,
                                    @PathVariable("port") int port,
                                    @PathVariable("oldid") int oldid){
        RegisterServerInfo registerServerInfo = new RegisterServerInfo();
        registerServerInfo.setServerId(serverid);
        registerServerInfo.setInIP(inip);
        registerServerInfo.setPort(port);
        try {
            relationService.registerFollower(registerServerInfo, oldid);
            return 1;
        }catch (Exception e){
            log.error("Register follower exception", e);
            return 0;
        }
    }

    /**
     *   relation/leader/{}/{}/{}", follower.getInIP(), follower.getPort(),
     * leader send info to follower
     * @param serverid
     * @param inip
     * @param port
     * @return
     */
    @GetMapping(value = "/relation/leader/{serverid}/{inip}/{port}")
    @ResponseBody
    public Integer leaderInfo(@PathVariable("serverid") int serverid,
                              @PathVariable("inip") String inip,
                              @PathVariable("port") int port){
        RegisterServerInfo registerServerInfo = new RegisterServerInfo();
        registerServerInfo.setServerId(serverid);
        registerServerInfo.setInIP(inip);
        registerServerInfo.setPort(port);
        try {
            relationService.leaderInfo(registerServerInfo);
            return 1;
        }catch (Exception e){
            log.error("leader info exception", e);
            return 0;
        }
    }

    // relation/remove/gw/{}", leader.getInIP(), leader.getPort(), gwsid);
    @GetMapping(value = "/relation/remove/gw/{gwid}")
    @ResponseBody
    public Integer removeGw(@PathVariable("gwid") int gwid){
        log.info("Remove gateway  tmsId {} {}", gwid, RegisterConfigInfoManager.getInstance().getRegisterServerInfo());
        ZebraExecutorManager.getInstance().getDisruptor(2).execute(() -> {
            serverRedisService.removeGw(gwid);
        });
        return 1;
    }

    // relation/remove/tms/{}", leader.getInIP(), leader.getPort(), tmsid);
    @GetMapping(value = "/relation/remove/tms/{tmsid}")
    @ResponseBody
    public Integer removeTms(@PathVariable("tmsid") int tmsid){
        log.info("Remove Tms  tmsId {} {}", tmsid, RegisterConfigInfoManager.getInstance().getRegisterServerInfo());
        ZebraExecutorManager.getInstance().getDisruptor(3).execute(() -> {
            TmsServerInfo serverInfo = serverRedisService.removeTms(tmsid);
            if (null != serverInfo){
                int serverType = serverInfo.getVfxs().contains("LOBBY,") ? 0 : 1;
                ZebraExecutorManager.getInstance().getDefaultScheduler().schedule(()->tmsOffline(tmsid, serverType), 60,  TimeUnit.SECONDS, ZebraExecutorManager.getInstance().getDefaultExecutor());
            }
        });
        return 1;
    }

    //serverType : lobby =0; tms = 1
    private void tmsOffline(int tmsid, int serverType){
        TmsServerInfo serverInfo = serverRedisService.getTmsById(tmsid);
        if (null == serverInfo){
            log.info("Offline schedule tmsid {} serType {}", tmsid, serverType);
            aucFeignService.tmsoff(tmsid, serverType);
        }
    }


}
